import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataOutput;
import java.io.IOException;

// 此处属性的名字，要和 json 的 key 保持一致
class Student {
    public int studentId;
    public int age;
}

@WebServlet("/studentInfo")
public class StudentInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 假设客户端发来的请求形如 /studentInfo?studentId=100&age=20
        // 就可以通过 getParameter 方法拿到这两个的值

        // 1. 获取 query String 中的传参
        // 2. Content-Type: application/x-www-form-urlencoded  form表单
        // 3. Content-Type: application/json                   JSON
        resp.setContentType("text/html; charset=utf8");
        String queryString = req.getQueryString();
        System.out.println(queryString);
        String studentId = req.getParameter("studentId");
        String age = req.getParameter("age");
        System.out.println("studentId: " + studentId + ", age: " + age);
        resp.getWriter().write("studentId: " + studentId + ", age: " + age);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("text/html; charset=utf8");
//        String queryString = req.getQueryString();
//        System.out.println(queryString);
//        String studentId = req.getParameter("studentId");
//        String age = req.getParameter("age");
//        System.out.println("studentId: " + studentId + ", age: " + age);
//        resp.getWriter().write("studentId: " + studentId + ", age: " + age);
//        System.out.println(req.getMethod());
//        doGet(req, resp);

        // 从请求的 body 中进行读取，并解析
        // 使用 readValue 来吧 json 字符串转成 java 对象
        // 第一个参数是一个 string 或者 InputStream
        // 第二个参数是转换的结果对应的 Java 类对象
        ObjectMapper objectMapper = new ObjectMapper();
        Student student = objectMapper.readValue(req.getInputStream(), Student.class);
        System.out.println(student.studentId + ", " + student.age);
        resp.getWriter().write("studentId: " + student.studentId + ", age: " + student.age);

        // java -> json
        Student s = new Student();
//        objectMapper.writeValue();

    }
}
